package com.it.reggie.config;

import com.it.reggie.Exception.SystemException;
import com.it.reggie.annotation.Log;
import com.it.reggie.commen.AsyncManager;
import com.it.reggie.entity.OperationLog;
import com.it.reggie.service.OperationLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.TimerTask;

@Component
@Aspect
@SuppressWarnings(value = "all")
public class aspect {

    @Autowired
    private OperationLogService logService;

    @Pointcut(value = "@annotation(com.it.reggie.annotation.Log)")
    public void pt(){}



    @Around("pt() && @annotation(logs)")
    public Object  method(ProceedingJoinPoint point, Log logs) throws Throwable {
        Object proceed = null;
        //执行目标方法

        //获取httpservletrequest
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=null;
        if(requestAttributes != null){
            request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        }
        Long userId = (Long) request.getSession().getAttribute("user");
        //point.getSignature():获取方法签名.getNamw()获取方法名称
        String name = point.getSignature().getName();
        OperationLog log = new OperationLog();

        log.setCreateTime(LocalDateTime.now());
        log.setAction(logs.value());
        try {
            proceed = point.proceed();
            log.setUserId(userId);
        } catch (Throwable throwable) {
            new AsyncManager().execute(new TimerTask() {
                @Override
                public void run() {
                    logService.save(log);
                }
            });
        }
        new AsyncManager().execute(new TimerTask() {
            @Override
            public void run() {
                logService.save(log);
            }
        });
        return proceed;
    }

}
